
#import "WWTCLTimer.h"
#import "WWTCLInterp.h"

@implementation WWTCLTimer

// function that does what's necessary to the object.  To maximise speed, 
// methodFor: is used.
void static wwtclTimerHandle(DPSTimedEntry tag, double now, char *userdata)
{
   WWTCLTimer *self = (id)userdata;

   self->value += self->incrementBy;
   self->syncCounter++;
   if (self->bFlags.sync && (self->syncCounter >= self->syncValue)) 
   {  [self synchronize:self];
      self->syncCounter = 0;
   }
   if (self->bFlags.wrap && (self->value >= self->wrapValue))
   {  self->value = self->startValue;
   }
   if (self->actionFunc)
   {  self->actionFunc(self->target, self->action, self);
   }

   [self evalCmd];

   return;
}

- evalCmd 
{  
   // the idea here is that we have some control string which we want
   // to send to the our interp outlet for it to evaluate.
   // the trick is to have already constructed the control string, 
   // or at least already know if we have to sprintf in our 
   // floating point value.
   [interp globalEval:tclCommand]; 
   return self; 
}

- startEntry
{
   if (entry != NULL) 
   {  [self stopEntry];
   }

   // get function for method, so we can be super-efficient
   if (target && action)
   {  actionFunc = [target methodFor:action];
   }

   // make a new timed entry
   entry = DPSAddTimedEntry(period,(DPSTimedEntryProc)wwtclTimerHandle, self, priority);

   // check it
   if ((int)entry == -1) 
   {  [self logError:"Couldn't start timer!\n"];
      entry = NULL;
      return nil;
   }
   return self;
}

- interp { return interp; }
- setInterp:newInterp { interp = newInterp; return self; }

- init
{
  [super init];

  controlStringSize = 32;
  controlString = (char *)NXZoneCalloc([self zone], controlStringSize, sizeof(char));
  tclCommandSize = 32;
  tclCommand = (char *)NXZoneCalloc([self zone], tclCommandSize, sizeof(char));

  return self;
}

- free
{
  if (controlString) { NXZoneFree([self zone], controlString); }
  if (tclCommand) { NXZoneFree([self zone], tclCommand); }
  return [super free];
}


@end
